package gui_layer;

import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.print.PrinterException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.DefaultCellEditor;
import javax.swing.ImageIcon;
import javax.swing.InputMap;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import javax.swing.table.TableCellEditor;

import model_layer.Product;
import model_layer.ProductPart;
import model_layer.Restock;
import model_layer.Supplier;
import ctr_layer.ProductCtr;
import ctr_layer.RestockCtr;
import ctr_layer.SupplierCtr;

public class NewRestockGUI extends SaleRestockNewWindow
{
	private Restock restock;
	private RestockCtr res_ctr;
	private ProductCtr prod_ctr;
	private SupplierCtr sup_ctr;
	private JComboBox<String> prod_box;
	private DynamicSearchComboBoxModel dscbm_p;
	private boolean can_proceed;
	private boolean correct_amount;
	private boolean correct_product;
	private boolean correct_retail_price;
	private boolean correct_profit;
	private boolean correct_sale_price;
	private ProductAdder pa;
	private SupplierSetter ss;
	protected String[] column_names = { "ID", "Name", "Amount", "Retail Price", "Profit %", "Sale Price", "Price for all" };
	/**
	 * Create the frame.
	 */
	public NewRestockGUI(Restock res)
	{
		super();
		setBounds(100, 100, 450, 300);
		JLabel lblSupplier = new JLabel("Supplier");
		lblSupplier.setFont(new Font("Helvetica Neue", Font.BOLD, 11));
		lblSupplier.setForeground(Color.WHITE);
		search_set_panel.add(lblSupplier);
		
		
		restock = res;
		prod_ctr = new ProductCtr();
		res_ctr = new RestockCtr();
		sup_ctr = new SupplierCtr();
		prepare_table(new Object[0][5], column_names);
		
		if(res != null)
		{
			make_as_details();
			this.setTitle("Restock Details");
			fill_data();
		}
		else
		{
			make_as_new();
			this.setTitle("New Restock");
			start_work_on_new_restock();
		}
		
		this.addInternalFrameListener(new InternalFrameAdapter()
		{
			@Override
			public void internalFrameClosing(InternalFrameEvent arg0)
			{
				if(pa != null)
				{
					pa.dispose();
				}
				if(ss != null)
				{
					ss.dispose();
				}
			}
		});
	}
	
	private void fill_data()
	{
		set_box.setSelectedItem(restock.getSupplier().getName());
		MyTableModel mtm = (MyTableModel) table.getModel();
		Object[] data; 
		for (ProductPart prod : restock.getProducts())
		{
			data = new Object[7];
			float ret_price = prod.getRetail_price();
			float sale_price = prod.getProduct().getPrice();
			data[0] = Integer.parseInt(prod.getProduct().getId());
			data[1] = prod.getProduct().getName();
			data[2] = prod.getAmount();
			data[3] = ret_price;
			data[4] = calculate_profit(ret_price, sale_price);
			data[5] = sale_price;
			data[6] = prod.getTotal_price();
			mtm.addRow(data);
		}
		price_lbl.setText(String.valueOf(restock.getTotal_price()));
	}
	
	private void start_work_on_new_restock()
	{
		prepare_table(new Object[1][7], column_names);

		can_proceed = false;
		restock = res_ctr.make_new_restock();
		table.setRowSorter(null);
		set_box_bindings();
		
		set_table_bindings();
		set_dynamic_search_fields();
		set_editable_columns();
		dscbm.start_anew();
		set_box.configureEditor(set_box.getEditor(), "");
		set_box.requestFocus();
		price_lbl.setText("0.0");
	}
	
	private void set_box_bindings()
	{
		dscbm.set_all_data(get_all_suppliers_names());
		Component c = set_box.getEditor().getEditorComponent();
		c.addKeyListener(new KeyAdapter()
		{
			@Override
			public void keyPressed(KeyEvent e)
			{
				if (e.getKeyChar() =='\n')
				{
					set_supplier();
					if (restock.getSupplier()!= null)
					{
						dscbm.set_handled(true);
						set_box.setBackground(Color.WHITE);
						set_box.setSelectedItem(restock.getSupplier().getName());
						price_lbl.setText(String.valueOf(restock.getTotal_price()));
						table.grabFocus();
						table.changeSelection(0, 1, false, false);
						if (table.editCellAt(0, 1))
				        {
				            Component editor = table.getEditorComponent();
				            editor.requestFocusInWindow();
				        }
						
						dscbm.set_handled(false);
					}
					else
					{
						set_box.setBackground(Color.RED);
					}
				}
			}
		});
		
		c.addFocusListener(new FocusAdapter()
		{
			@Override
			public void focusLost(FocusEvent e)
			{
				
				if(!dscbm.is_handled())
				{
					
					set_supplier();
					if (restock.getSupplier()!= null)
					{
						price_lbl.setText(String.valueOf(restock.getTotal_price()));
						set_box.setBackground(Color.WHITE);
						set_box.setSelectedItem(restock.getSupplier().getName());
					}
					else
					{
						set_box.setBackground(Color.RED);
					}
				}
			}
		});
	}
	
	private void set_table_bindings()
	{
		InputMap map = table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
		map.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "strange go right");
		ActionMap a_map = table.getActionMap();
		a_map.put("strange go right", new AbstractAction()
		{
			private static final long serialVersionUID = 1L;

			@Override
			public void actionPerformed(ActionEvent e)
			{
				int row = table.convertRowIndexToModel(table.getSelectedRow());
				int column = table.convertColumnIndexToModel(table.getSelectedColumn());
				TableCellEditor editor = table.getCellEditor();
				if(editor != null)
				{
					editor.stopCellEditing();
				}
				else
				{
					perform_checks();
				}
				if(column == 1)
				{
					if(can_proceed)
					{
						table.editCellAt(row, column + 1);
						table.changeSelection(row, column +1, false, false);
					}
				}
				else if (column == 2)
				{
					if(can_proceed)
					{
						if(is_inserted(String.valueOf(table.getValueAt(row, 3))))
						{
							table.changeSelection(row + 1, 1, false, false);
							if (table.editCellAt(row + 1, 1))
					        {
					            Component comp = table.getEditorComponent();
					            comp.requestFocusInWindow();
					        }	
						}
						else
						{
							table.changeSelection(row, column + 1, false, false);
							table.getModel().setValueAt("", row, column + 1);
							table.editCellAt(row, column + 1);
						}
					}
				}
				else if(column == 3 || column == 4 || column ==  5)
				{
					if(can_proceed)
					{
						table.changeSelection(row + 1, 1, false, false);
						if (table.editCellAt(row + 1, 1))
				        {
				            Component comp = table.getEditorComponent();
				            comp.requestFocusInWindow();
				        }	
					}
				}
				can_proceed = false;
			}
		});
	}
	
	private void set_editor_options(TableCellEditor editor)
	{
		editor.addCellEditorListener(new CellEditorListener()
		{
			@Override
			public void editingStopped(ChangeEvent arg0)
			{
				if(!dscbm_p.is_handled())
				{
					perform_checks();
				}
			}
			@Override
			public void editingCanceled(ChangeEvent arg0)
			{
				// TODO Auto-generated method stub
				
			}
		});
	}
	
	private void set_dynamic_search_fields()
	{
		prod_box = new JComboBox<String>();
		
		prod_box.setEditable(true);
		dscbm_p = new DynamicSearchComboBoxModel(prod_box);
		List<String> data = get_all_prod_names();
		dscbm_p.set_all_data(data);
		prod_box.addItemListener(dscbm_p);
		prod_box.addKeyListener(dscbm_p);
		prod_box.setModel(dscbm_p);
		Component c = prod_box.getEditor().getEditorComponent();
		c.addKeyListener(new KeyAdapter()
		{
			@Override
			public void keyReleased(KeyEvent e)
			{
				if (e.getKeyChar() =='\n')
				{
					dscbm_p.set_handled(true);
					ProductPart part = check_correct_product();
					if(part != null)
					{
						int row = table.convertRowIndexToModel(table.getSelectedRow());
						table.changeSelection(row, 2, false, false);
						table.editCellAt(row, 2);
						dscbm_p.start_anew();
						prod_box.configureEditor(prod_box.getEditor(), "");
						fill_row_with_product_part_data(part, row);
						try_to_add_new_row();
					}

					dscbm_p.set_handled(false);
				}
			}
		});
		
		table.getColumnModel().getColumn(1).setCellEditor(new ComboBoxCellEditor(prod_box));
		ComboBoxCellEditor editor = (ComboBoxCellEditor) table.getColumnModel().getColumn(1).getCellEditor();
		set_editor_options(editor);
		
		for(int i = 2; i < 6; i++)
		{
			table.getColumnModel().getColumn(i).setCellEditor(new DefaultCellEditor(new JTextField()));
			DefaultCellEditor editor_d = (DefaultCellEditor) table.getColumnModel().getColumn(i).getCellEditor();
			set_editor_options(editor_d);
		}
	}
	
	private void perform_checks()
	{
		int row = table.convertRowIndexToModel(table.getSelectedRow());
		int column = table.convertColumnIndexToModel(table.getSelectedColumn());
		ProductPart part = null;
		if(column == 1)
		{
			System.out.println("Performing product_check");
			part = check_correct_product();
			if(part != null)
			{
				dscbm_p.start_anew();
				prod_box.configureEditor(prod_box.getEditor(), "");
			}
		}
		else if (column == 2)
		{
			System.out.println("Performing amount_check");
			part = check_correct_amount();			
		}
		else if (column == 3)
		{
			System.out.println("Performing retail_price_check");
			part = check_correct_retail_price();	
		}
		else if( column == 4)
		{
			System.out.println("Performing profit_check");
			part = check_correct_profit();	
		}
		else if (column == 5)
		{
			System.out.println("Performing sale_price_check");
			part = check_correct_sale_price();	
		}
		
		if (part != null)
		{
			fill_row_with_product_part_data(part, row);
		}
		System.out.println(correct_product);
		try_to_add_new_row();
		
		update_restock();
	}
	
	private void try_to_add_new_row()
	{
		if(can_proceed)
		{
			if(correct_amount && correct_product && correct_retail_price && correct_profit && correct_sale_price)
			{
				res_ctr.add_current_product_part();
				System.out.println("ADD CURRENT PRODUCT PART");
				
				MyTableModel mtm = (MyTableModel) table.getModel();
				correct_amount = false;
				correct_retail_price = false;
				correct_profit = false;
				correct_sale_price = false;
				correct_product = false;
				//fill_row_with_product_part_data(part, row);
				mtm.addRow(new Object[7]);
			}
		}
	}
	
	private ProductPart check_correct_amount()
	{
		can_proceed = false;
		int current_row =  table.getSelectedRow();
		int current_column = table.getSelectedColumn();
		ProductPart part = null;
		if(current_row != -1)
		{
			current_row = table.convertRowIndexToModel(current_row);
			current_column = table.convertRowIndexToModel(current_column);
			String amount = table.getModel().getValueAt(current_row, current_column).toString();
			String current_id = String.valueOf(table.getModel().getValueAt(current_row, 0));
			boolean finished_row = (table.getModel().getRowCount() - 1)  != current_row;
			int i_amount = -1;
			System.out.println(amount);
			
			if(is_integer(amount))
			{
				i_amount = Integer.parseInt(amount);
				System.out.println(i_amount);
				can_proceed =  i_amount > 0;
			}
			
			if(can_proceed)
			{
				if(finished_row)
				{
					part = res_ctr.update_amount(current_id, i_amount);
					System.out.println("UPDATE AMOUNT");

				}
				else
				{
					part = res_ctr.set_amount(i_amount);
					System.out.println("SET AMOUNT");
					if(part != null)
					{
						correct_amount = true;
					}
					else
					{
						correct_amount = false;
					}
					
				}
			}
			MarkingCellRenderer renderer = (MarkingCellRenderer) table.getCellRenderer(current_row, current_column);
			if(part != null)
			{
				renderer.remove_incorrect_cell(current_row);
			}
			else
			{
				renderer.add_incorrect_cell(current_row);
			}
		}
		return part;
	}
	
	private ProductPart check_correct_product()
	{

		int current_row = table.getSelectedRow();
		int current_column = table.getSelectedColumn();
		can_proceed = false;
		ProductPart part = null;
		
		if(current_row != -1)
		{
			current_row = table.convertRowIndexToModel(current_row);
			current_column = table.convertColumnIndexToModel(current_column);
			String id_name = (String) prod_box.getEditor().getItem();
			prod_box.setSelectedItem(id_name);
			System.out.println("Product data: " + id_name);
			String old_id = String.valueOf(table.getModel().getValueAt(current_row, 0));
			
			boolean finished_row = table.getModel().getValueAt(current_row, 6) != null;
			if(finished_row)
			{
				if(is_integer(id_name))
				{
					part = res_ctr.update_product_by_id(old_id, id_name);
					System.out.println("UPDATE PRODUCT BY ID");
				}
				else
				{
					part = res_ctr.update_product_by_name(old_id, id_name);
					System.out.println("UPDATE PRODUCT BY NAME");
				}
			}
			else
			{
				if(is_integer(id_name))
				{
					part = res_ctr.set_product_by_id(id_name);
					System.out.println("SET PRODUCT BY ID");
				}
				else
				{
					part = res_ctr.set_product_by_name(id_name);
					System.out.println("SET PRODUCT BY NAME");
				}
				if(part != null)
				{
					correct_product = true;
				}
				else
				{
					correct_product = false;
				}
			}
			can_proceed = part != null;
			MarkingCellRenderer renderer = (MarkingCellRenderer) table.getCellRenderer(current_row, current_column);
			if (!can_proceed)
			{
				renderer.add_incorrect_cell(current_row);
				table.repaint();
			}
			else
			{
				renderer.remove_incorrect_cell(current_row);
			}
		}
		return part;
	}
	
	private ProductPart check_correct_retail_price()
	{
		can_proceed = false;
		int current_row =  table.getSelectedRow();
		int current_column = table.getSelectedColumn();
		ProductPart part = null;
		if(current_row != -1)
		{
			current_row = table.convertRowIndexToModel(current_row);
			current_column = table.convertRowIndexToModel(current_column);
			String r_price = table.getModel().getValueAt(current_row, current_column).toString();
			String current_id = String.valueOf(table.getModel().getValueAt(current_row, 0));
			boolean finished_row = (table.getModel().getRowCount() - 1)  != current_row;
			float retail_price = -1;
			System.out.println(r_price);
			
			if(is_float(r_price))
			{
				retail_price = Float.parseFloat(r_price);
				System.out.println(retail_price);
				can_proceed =  retail_price > 0;
			}
			
			if(can_proceed)
			{
				if(finished_row)
				{
					part = res_ctr.update_retail_price(current_id, retail_price);
					System.out.println("UPDATE RETAIL PRICE");

				}
				else
				{
					part = res_ctr.set_retail_price(retail_price);
					System.out.println("SET RETAIL PRICE");
					if(part != null)
					{
						correct_retail_price = true;
					}
					else
					{
						correct_retail_price = false;
					}

				}
			}
			MarkingCellRenderer renderer = (MarkingCellRenderer) table.getCellRenderer(current_row, current_column);
			if(part != null)
			{
				renderer.remove_incorrect_cell(current_row);
			}
			else
			{
				renderer.add_incorrect_cell(current_row);
			}

		}
		return part;
	}
	
	private ProductPart check_correct_profit()
	{
		can_proceed = false;
		int current_row =  table.getSelectedRow();
		int current_column = table.getSelectedColumn();
		ProductPart part = null;
		if(current_row != -1)
		{
			current_row = table.convertRowIndexToModel(current_row);
			current_column = table.convertRowIndexToModel(current_column);
			String profit = table.getModel().getValueAt(current_row, current_column).toString();
			String current_id = String.valueOf(table.getModel().getValueAt(current_row, 0));
			boolean finished_row = (table.getModel().getRowCount() - 1)  != current_row;
			float f_profit = -1;
			System.out.println(profit);
			
			if(is_float(profit))
			{
				f_profit = Float.parseFloat(profit);
				System.out.println(f_profit);
				can_proceed =  f_profit > 0;
			}
			
			if(can_proceed)
			{
				if(finished_row)
				{
					part = res_ctr.update_profit(current_id, f_profit);
					System.out.println("UPDATE PROFIT");


				}
				else
				{
					part = res_ctr.set_profit(f_profit);
					System.out.println("SET PROFIT");
					if(part != null)
					{
						correct_profit = true;
					}
					else
					{
						correct_profit = false;
					}
				}
			}
			
			MarkingCellRenderer renderer = (MarkingCellRenderer) table.getCellRenderer(current_row, current_column);
			if(part != null)
			{
				renderer.remove_incorrect_cell(current_row);
			}
			else
			{
				renderer.add_incorrect_cell(current_row);
			}
		}
		return part;
	}
	
	private ProductPart check_correct_sale_price()
	{
		can_proceed = false;
		int current_row =  table.getSelectedRow();
		int current_column = table.getSelectedColumn();
		ProductPart part = null;
		if(current_row != -1)
		{
			current_row = table.convertRowIndexToModel(current_row);
			current_column = table.convertRowIndexToModel(current_column);
			
			String sale_price = table.getModel().getValueAt(current_row, current_column).toString();
			String current_id = String.valueOf(table.getModel().getValueAt(current_row, 0));
			boolean finished_row = (table.getModel().getRowCount() - 1)  != current_row;
			float f_sale_price = -1;
			System.out.println(sale_price);
			
			if(is_float(sale_price))
			{
				f_sale_price = Float.parseFloat(sale_price);
				System.out.println(f_sale_price);
				can_proceed =  f_sale_price > 0;
			}
			
			if(can_proceed)
			{
				if(finished_row)
				{
					part = res_ctr.update_sale_price(current_id, f_sale_price);
					System.out.println("UPDATE PROFIT");
				}
				else
				{
					part = res_ctr.set_sale_price(f_sale_price);
					System.out.println("SET PROFIT");
					if(part != null)
					{
						correct_sale_price = true;
					}
					else
					{
						correct_sale_price = false;
					}
				}
			}
			
			MarkingCellRenderer renderer = (MarkingCellRenderer) table.getCellRenderer(current_row, current_column);
			if(part != null)
			{
				renderer.remove_incorrect_cell(current_row);
			}
			else
			{
				renderer.add_incorrect_cell(current_row);
			}
		}
		return part;
	}
	
	
	
	private void fill_row_with_product_part_data(ProductPart part, int row)
	{
		MyTableModel model = (MyTableModel) table.getModel();
		boolean is_last_row = (model.getRowCount() -1) == row;
		MarkingCellRenderer renderer; 
		if(part.getProduct() != null)
		{
			model.setValueAt(Integer.parseInt(part.getProduct().getId()), row, 0);
			model.setValueAt(part.getProduct().getName(), row, 1);
			model.setValueAt(part.getProduct().getPrice(), row, 5);
			renderer = (MarkingCellRenderer) table.getCellRenderer(row, 5);
			renderer.remove_incorrect_cell(row);
			if(is_last_row)
			{
				correct_sale_price = true;
			}
			if(part.getRetail_price() != 0)
			{
				model.setValueAt(part.getRetail_price(), row, 3);
				model.setValueAt(calculate_profit(part.getRetail_price(), part.getProduct().getPrice()), row, 4);
				renderer = (MarkingCellRenderer) table.getCellRenderer(row, 3);
				if(part.getRetail_price() > part.getProduct().getPrice())
				{
					renderer.add_incorrect_cell(row);
					renderer = (MarkingCellRenderer) table.getCellRenderer(row, 4);
					renderer.add_incorrect_cell(row);
				}
				else
				{
					renderer.remove_incorrect_cell(row);
					renderer = (MarkingCellRenderer) table.getCellRenderer(row, 4);
					renderer.remove_incorrect_cell(row);
				}
				
				if(is_last_row)
				{
					if(part.getRetail_price() > part.getProduct().getPrice())
					{
						correct_retail_price = false;
						correct_profit = false;
					}
					else
					{
						correct_retail_price = true;
						correct_profit = true;
					}
					
				}
			}
			if(part.getTotal_price() != 0)
			{
				model.setValueAt(part.getTotal_price(), row, 6);
			}
		}
		
		if(part.getAmount() != 0)
		{
			model.setValueAt(part.getAmount(), row, 2);
			if(is_last_row)
			{
				correct_amount = true;
			}
		}
		else if(is_last_row)
		{
			correct_amount = false;
		}
	}
	
	private void fill_last_row_with_product_part_data(ProductPart part)
	{
		int last_row = table.getModel().getRowCount() - 1;
		fill_row_with_product_part_data(part, last_row);
		MarkingCellRenderer mcr = (MarkingCellRenderer) table.getCellRenderer(last_row, 2);
		if(part.getAmount() != 0)
		{
			mcr.remove_incorrect_cell(last_row);
			table.repaint();
		}
		mcr = (MarkingCellRenderer) table.getCellRenderer(last_row, 1);
		mcr.remove_incorrect_cell(last_row);
	}
	
	private void update_restock()
	{
		restock = res_ctr.get_current_restock();
		price_lbl.setText(String.valueOf(restock.getTotal_price()));
	}
	
	private void set_supplier()
	{
		String sup_data = (String) set_box.getEditor().getItem();
		set_box.setSelectedItem(sup_data);
		System.out.println(sup_data);

		if (is_integer(sup_data))
		{
			restock = res_ctr.set_supplier_with_id(sup_data);
		}
		else
		{
			restock = res_ctr.set_supplier_with_name(sup_data);
		}
	}
	
	private boolean is_everything_ok()
	{
		if(set_box.getBackground().equals(Color.RED) || restock.getSupplier() == null)
		{
			return false;
		}
		int rows = table.getModel().getRowCount();
		if(rows-1 == 0)
		{
			return false;
		}
		for(int i = 0; i < rows-1; i++)
		{
			for(int j = 1; j < 6; j ++)
			{
				Component cell = table.prepareRenderer(table.getCellRenderer(i, j), i, j);
				if(cell.getBackground().equals(Color.RED))
				{
					return false;
				}
			}
		}
		return true;
	}
	
	private boolean is_last_row_empty()
	{
		int last_row = table.getModel().getRowCount() - 1;
		for(int i = 1; i < 6; i++)
		{
			if(!(table.getModel().getValueAt(last_row, i) == null || table.getModel().getValueAt(last_row, i).equals("")))
			{
				return false;
			}
		}		
		return true;
	}
	
	private List<String> get_all_prod_names()
	{

		List<Product> products = prod_ctr.find_non_deleted_products();
		List<String> names_ids = new ArrayList<String>();
		for(Product prod : products)
		{
			names_ids.add(prod.getName());
		}
		return names_ids;
	}
	
	private List<String> get_all_suppliers_names()
	{
		List<String> ids_names = new ArrayList<String>();
		List<Supplier> suppliers = sup_ctr.get_non_deleted_suppliers();
		for(Supplier sup : suppliers)
		{
			ids_names.add(sup.getName());
		}
		return ids_names;
	}
	
	private float calculate_profit(float retail_price, float sale_price)
	{
		return (sale_price - retail_price) / retail_price * 100;
	}
	
	private boolean is_inserted(String text)
	{
		try
		{
			float f = Float.parseFloat(text);
			return f > 0;
		}
		catch(NumberFormatException e){}
		return false;
	}

	@Override
	protected void search()
	{
		ss = new SupplierSetter();
		this.getDesktopPane().add(ss);
		Point window_corner = this.getLocation();
		ss.setLocation((int) window_corner.getX() + 15, (int) window_corner.getY() + 15);
		ss.setVisible(true);
	}

	@Override
	protected void add_product()
	{
		pa = new ProductAdder();
		this.getDesktopPane().add(pa);
		Point window_corner = this.getLocation();
		pa.setLocation((int) window_corner.getX() + 15, (int) window_corner.getY() + 15);
		pa.setVisible(true);
	}

	@Override
	protected void save()
	{
		if(is_everything_ok())
		{
			boolean save;
			if(is_last_row_empty())
			{
				save = JOptionPane.showConfirmDialog(this, "Are you sure you want to save the restock?\n ", 
						"Save sale?", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION;
			}
			else
			{
				save = JOptionPane.showConfirmDialog(this, "Are you sure you want to save the restock?\n "
						+ "The last row is not empty, it will however, not be saved since it wasn't entered fully.\n"
						+ "Continuing will save the sale without last row.", "Save restock?", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION;
			}
			while(save)
			{
				if(res_ctr.save_restock())
				{
					/*if(JOptionPane.showConfirmDialog(this, "Restock was saved successfully! \n"
							+ "Do you wish to make a new restock?","Success!", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
					{*/
						start_work_on_new_restock();
					/*}
					else
					{
						dispose();
						fireInternalFrameEvent(InternalFrameEvent.INTERNAL_FRAME_CLOSING);
					}*/
					save = false;
					
				}
				else
				{
					save = (JOptionPane.showConfirmDialog(this, "An error occured while adding a restock. \n"
						+ "Do you wish to try again?", "Error", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION);
				}
				
			}
		}
		else
		{
			JOptionPane.showMessageDialog(this, "Restock cannot be added because some data were typed incorrectly, "
					+ "or no products were added.","Cannot add restock", JOptionPane.ERROR_MESSAGE);
		}		
	}

	@Override
	protected void delete()
	{
		int row = table.convertRowIndexToModel(table.getSelectedRow());
		int last_row = table.getModel().getRowCount() - 1;
		if(row != -1)
		{
			if(!(row == last_row))
			{
				if(JOptionPane.showConfirmDialog(this, "Are you sure you wish to remove this product from restock?",
						"Remove product", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
				{
					MyTableModel mtm = (MyTableModel) table.getModel();
					String id = mtm.getValueAt(row, 0).toString();
					res_ctr.remove_product(id);
					if(table.getEditingColumn()== 1)
					{
						table.getCellEditor().cancelCellEditing();
					}
					mtm.removeRow(row);
				}
			}
			else
			{
				MyTableModel mtm = (MyTableModel) table.getModel();
				mtm.removeRow(last_row);
				mtm.addRow(new Object[5]);
				correct_product = false;
				correct_amount = false;
			}
			MarkingCellRenderer mcr;
			for (int i = 1; i < 6; i ++)
			{
				mcr = (MarkingCellRenderer) table.getCellRenderer(row, i);
				mcr.revalidate_after_delete(row);
			}
			
			table.repaint();
			update_restock();
		}
		
	}

	@Override
	protected void set_editable_columns()
	{
		MyTableModel mtm = (MyTableModel) table.getModel();
		for(int i = 1; i < 6; i++)
		{
			mtm.add_editable_column(i);
			table.getColumnModel().getColumn(i).setCellRenderer(new MarkingCellRenderer());
		}
	}
	
	private void cancel_last_row_edit()
	{
		int last_row = table.convertRowIndexToModel(table.getRowCount()) - 1;
		for (int i = 1; i < 6; i ++)
		{
			table.getCellEditor(last_row, i).cancelCellEditing();;
		}
	}
	
	private void add_row()
	{
		MyTableModel mtm = (MyTableModel) table.getModel();
		mtm.addRow(new Object[7]);
		correct_product = false;
		correct_amount = false;
		correct_profit = false;
		correct_retail_price = false;
		correct_sale_price = false;
		update_restock();
	}
	
	class ProductAdder extends AddProductGUI
	{
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		public ProductAdder()
		{
			super();
		}
		
		@Override
		protected void set_or_add()
		{
			int row = table.getSelectedRow();
			if(row != -1)
			{
				row = table.convertRowIndexToModel(row);
				String id = String.valueOf(table.getModel().getValueAt(row, 0));
				System.out.println(id);
				ProductPart part = res_ctr.set_product_by_id(id);
				if(part != null)
				{
					cancel_last_row_edit();
					dscbm_p.start_anew();
					prod_box.configureEditor(prod_box.getEditor(), "");
					fill_last_row_with_product_part_data(part);
					correct_product = true;
					boolean end = false;
					while(!end)
					{
						String amount = JOptionPane.showInputDialog(this, "Please input amount of product");
						if(amount == null)
						{
							end = true;
						}
						else
						{
							if(is_integer(amount))
							{
								int i_amount = Integer.parseInt(amount);
								if(i_amount > 0)
								{
									res_ctr.set_amount(i_amount);
									if(part.getRetail_price() != 0)
									{
										part = res_ctr.add_current_product_part();
										fill_last_row_with_product_part_data(part);
										correct_amount = true;
										add_row();
										end = true;
									}
									else
									{
										fill_last_row_with_product_part_data(part);
										while (!end)
										{
											String retail_price = JOptionPane.showInputDialog(this, "Please input retail price of product");
											if(retail_price == null)
											{
												end = true;
											}
											else
											{
												if(is_float(retail_price))
												{
													float f_retail_price = Float.parseFloat(retail_price);
													if(f_retail_price < part.getProduct().getPrice())
													{
														res_ctr.set_retail_price(f_retail_price);
														part = res_ctr.add_current_product_part();
														fill_last_row_with_product_part_data(part);
														add_row();
														end = true;
													}
													else JOptionPane.showMessageDialog(this, "Retail price must be smaller than sale price.",
															"Incorrect retail price", JOptionPane.ERROR_MESSAGE);
												}
												else JOptionPane.showMessageDialog(this, "Retail price must be a number.", 
														"Incorrect retail price", JOptionPane.ERROR_MESSAGE);
											}
										}
									}
									
								}
								else JOptionPane.showMessageDialog(this, "Amount must be greater than 0.", "Incorrect amount", JOptionPane.ERROR_MESSAGE);
							}
							else JOptionPane.showMessageDialog(this, "Amount must be a number.", "Incorrect amount", JOptionPane.ERROR_MESSAGE);
						}
					}
				}
				else
				{
					JOptionPane.showMessageDialog(this, "The product was already added!\nChoose a different one.",
							"Product already present", JOptionPane.PLAIN_MESSAGE);
				}
			}
		}
	}
	@SuppressWarnings("serial")
	class SupplierSetter extends SetSupplierGUI
	{
		public SupplierSetter()
		{
			super();
		}
		
		@Override
		protected void set_or_add()
		{
			{
				int row = table.getSelectedRow();
				if(row != -1)
				{
					row = table.convertRowIndexToModel(row);
					String id = String.valueOf(table.getModel().getValueAt(row, 0));
					System.out.println(id);
					restock = res_ctr.set_supplier_with_id(id);
					if(restock.getSupplier() != null)
					{
						set_box.setSelectedItem(restock.getSupplier().getName());
						set_box.setBackground(Color.WHITE);
					}
					this.dispose();
					
				}
			}
			
		}
		
	}

}
